package com.faya.green.controller.main;

import com.faya.green.abnormal.ControllerException;
import com.faya.green.abnormal.ServiceException;
import com.faya.green.controller.BaseController;
import com.faya.green.enumeration.ResultEnum;
import com.faya.green.model.Authority;
import com.faya.green.model.ResultJson;
import com.faya.green.model.Role;
import com.faya.green.model.User;
import com.faya.green.model.web.UserPostOrgWeb;
import com.faya.green.model.web.UserRoleAuthor;
import com.faya.green.service.*;
import com.faya.green.utils.CommonUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author ：LX
 * 创建时间： 2018/10/20. 11:57
 * 地点：广州
 * 目的: 权限控制器
 * 备注说明：
 */
@Controller
@RequestMapping("/author")
public class AuthorityController extends BaseController {

    @Autowired
    private AuthorityService authorityService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;


    /**
     * 展示角色拥有的权限
     * @param roleId 角色ID
     * @return 权限 字符串
     */
    @RequestMapping(value = "/showAuthor.php", method = RequestMethod.POST)
    @ResponseBody
    public ResultJson showAuthor(String roleId){
        try {

            List<Authority> authorList = authorityService.getAuthorByRoleId(roleId);
            StringBuffer sb = new StringBuffer();
            if (authorList != null && authorList.size() > 0){
                for (Authority authority : authorList){
                    sb.append(authority.getChBoundary());
                    sb.append("<br/>");
                }
            }
            return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), sb.toString(), null);

        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "授权失败", null);
        }
    }

    /**
     * 删除用户的角色
     * @param id 角色ID
     * @param uid 用户ID
     * @return
     */
    @RequiresPermissions("user:sys.role:del")
    @RequestMapping(value = "/delUserRole.php", method = RequestMethod.POST)
    @ResponseBody
    public ResultJson delUserRole(String id, String uid){
        try {

            userService.delUserRole(id, uid);
            return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "删除用户角色成功", null);

        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "删除用户角色失败", null);
        }
    }


    /**
     * 用户的角色授予
     * @param roleArr 角色数组
     * @param id 用户id
     */
    @RequestMapping(value = "/addUserAuthor.php", method = RequestMethod.POST)
    @ResponseBody
    public ResultJson addUserAuthor(String[] roleArr, String id){
        try {

            userService.addUserRole(roleArr, id);
            return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "授权成功", null);

        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "授权失败", null);
        }
    }


    /**
     * 跳转到授予角色页面
     * @param uid 用户id
     * @param ucreateUser 创建人ID，可以看做是父ID
     * @return
     * @throws ControllerException
     */
    @RequestMapping(value = "/userAuthorizationUrl.php", method = RequestMethod.GET)
    public String userAuthorizationUrl(String uid, String ucreateUser, ModelMap modelMap) throws ControllerException {
        if (CommonUtils.checkNull(ucreateUser) || CommonUtils.checkNull(uid)){
            throw new ControllerException("非法请求，请检查数据");
        }

        //父用户创建的角色和拥有的角色
        List<Role> userByRoleCreatRole = roleService.getUserByRoleCreatRole(ucreateUser);
        //子用户拥有的角色
        List<Role> userByRole = roleService.getUserByRole(uid);

        User user = userService.getUserById(uid);
        modelMap.put("userByRoleCreatRole", userByRoleCreatRole);
        modelMap.put("userByRole", userByRole);
        modelMap.put("userAuthor", user);

        modelMap.put("choiceView", "userAuthor");

        return "/common/trunk";
    }

    /**
     * 获取用户机构岗位信息(自己创建的用户)
     * @param page 页码
     * @param limit 每页数据
     * @return
     */
    @RequestMapping(value = "/getUserList.php", method = RequestMethod.POST)
    @ResponseBody
    public ResultJson getUserList(Integer page, Integer limit){
        try {

            Subject subject = SecurityUtils.getSubject();
            User user = (User)subject.getPrincipal();

            if (page == null || limit == null || page < 0 || limit < 0){
                PageHelper.startPage(1, 10);
            } else {
                //这段代码表示，程序开始分页了，page默认值是1，pageSize默认是10，意思是从第1页开始，每页显示10条记录
                PageHelper.startPage(page, limit);
            }

            List<UserPostOrgWeb> userPostOrgWebList = userService.getUserPostOrgWebByCreateUser(user.getId());
            PageInfo<UserPostOrgWeb> pageInfo = new PageInfo<UserPostOrgWeb>(userPostOrgWebList);
            return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "获取用户机构岗位信息成功", pageInfo);

        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "获取用户机构岗位信息失败", null);
        }
    }



    /**
     * 跳转到用户角色页面
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/userViewUrl.php", method = RequestMethod.GET)
    public String userViewUrl(ModelMap modelMap){
        //index页面展示哪一个页面
        modelMap.put("choiceView", "userView");

        return "/common/trunk";
    }



    /**
     * 新增或修改一个角色
     * @param role 角色数据
     * @param authorArr 权限
     * @return
     */
    @PostMapping("/addOrUpdRole.php")
    @ResponseBody
    @RequiresPermissions(value = {"user:sys.role:add", "user:sys.role:upd"}, logical = Logical.OR)
    public ResultJson addOrUpdRole(Role role, String[] authorArr){
        try {
            String id = role.getId();
            roleService.addOrUpdRole(role, authorArr);
            if (CommonUtils.checkNull(id)){
                return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "新增角色成功", null);
            } else {
                return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "更新角色成功", null);
            }

        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            if (CommonUtils.checkNull(role.getId())){
                return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "新增角色失败", null);
            } else {
                return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "更新角色失败", null);
            }
        }
    }

    /**
     * 删除角色
     * @param roleId 角色id
     * @return
     */
    @PostMapping("/delRole.php")
    @ResponseBody
    @RequiresPermissions("user:sys.role:del")
    public ResultJson delRole(String roleId){
        try {

            roleService.delLogicRole(roleId);
            return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "删除角色成功", null);

        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "删除角色失败", null);
        }
    }

    /**
     * 跳转到新增或者更新的角色页面
     * @param roleId 更新时候有，角色的ID
     * @param addOrUpd 添加还是删除 add upd 两种类型
     * @return
     */
    @RequiresPermissions(value = {"user:sys.role:add", "user:sys.role:upd"}, logical = Logical.OR)
    @RequestMapping(value = "/toAddOrUpdRoleUrl.php", method = RequestMethod.GET)
    public String toAddOrUpdRoleUrl(String roleId, String addOrUpd, ModelMap modelMap) throws ControllerException {

        if (CommonUtils.checkNull(addOrUpd)){
            throw new ControllerException("无法判定操作类型");
        }
        if ("upd".equals(addOrUpd)){
            if (CommonUtils.checkNull(roleId)){
                throw new ServiceException("非法请求，不能获取角色");
            }
        }

        //查询出当前用户所拥有的权限
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        //保存权限
        List<UserRoleAuthor> userRoleAuthorList = authorityService.getUserRoleAuthorByUid(user.getId());
        modelMap.put("userRoleAuthorList", userRoleAuthorList);

        modelMap.put("addOrUpd", addOrUpd);
        modelMap.put("choiceView", "roleAddUpd");
        if (!CommonUtils.checkNull(roleId)){
            Role role = roleService.getRoleById(roleId);
            modelMap.put("role", role);
        }

        return "/common/trunk";
    }



    /**
     * 获取当前用户创建的 全部的角色
     * @param page 页码
     * @param limit 每页数量
     * @return
     */
    @RequestMapping(value = "/getRoleList.php", method = RequestMethod.POST)
    @ResponseBody
    public ResultJson getRoleList(Integer page, Integer limit){
        try {


            Subject subject = SecurityUtils.getSubject();
            User user = (User)subject.getPrincipal();
            if (page == null || limit == null || page < 0 || limit < 0){
                PageHelper.startPage(1, 10);
            } else {
                //这段代码表示，程序开始分页了，page默认值是1，pageSize默认是10，意思是从第1页开始，每页显示10条记录
                PageHelper.startPage(page, limit);
            }
            List<Role> roleList = roleService.getRoleByUserId(user.getId());
            PageInfo<Role> pageInfo = new PageInfo<Role>(roleList);
            return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "获取角色信息成功", pageInfo);

        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "获取角色信息失败", null);
        }
    }


    /**
     * 跳转到全部角色展示页面
     * @param modelMap
     * @return
     */
    @RequiresPermissions("user:sys.role:query")
    @RequestMapping(value = "/listRoleViewUrl.php", method = RequestMethod.GET)
    public String listRoleViewUrl(ModelMap modelMap){
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        modelMap.put("userRole", user);
        //index页面展示哪一个页面
        modelMap.put("choiceView", "roleView");

        return "/common/trunk";
    }

    /**
     * 分页获取 用户权限数据
     * @param page 页码
     * @param limit 每页数量
     * @return
     */
    @RequestMapping(value = "/getAuthorList.php", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("admin:sys.author:query")
    public ResultJson getAuthorList(Integer page, Integer limit){
        try {

            if (page == null || limit == null || page < 0 || limit < 0){
                PageHelper.startPage(1, 10);
            } else {
                //这段代码表示，程序开始分页了，page默认值是1，pageSize默认是10，意思是从第1页开始，每页显示10条记录
                PageHelper.startPage(page, limit);
            }
            List<Authority> authorities = authorityService.getAuthorList();
            PageInfo<Authority> pageInfo = new PageInfo<Authority>(authorities);
            return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "获取权限信息成功", pageInfo);

        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "获取权限信息失败", null);
        }
    }


    /**
     * 跳转到权限的展示页面
     * @return
     */
    @RequestMapping(value = "/listAuthorityViewUrl.php", method = RequestMethod.GET)
    @RequiresPermissions("admin:sys.author:query")
    public String listAuthorityViewUrl(ModelMap modelMap){
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        modelMap.put("userAuthor", user);
        //index页面展示哪一个页面
        modelMap.put("choiceView", "authorView");

        return "/common/trunk";
    }

    /**
     * 跳转到新增或者更新的权限页面
     * @param authorId 更新时候有，权限的ID
     * @param addOrUpd 添加还是删除 add upd 两种类型
     * @return
     */
    @RequestMapping(value = "/toAddOrUpdAuthorUrl.php", method = RequestMethod.GET)
    @RequiresPermissions(value = {"admin:sys.author:add", "admin:sys.author:upd"}, logical = Logical.OR)
    @RequiresRoles("admin")
    public String toAddOrUpdAuthorUrl(String authorId, String addOrUpd, ModelMap modelMap) throws ControllerException {
        if (CommonUtils.checkNull(addOrUpd)){
            throw new ControllerException("无法判定操作类型");
        }
        if ("upd".equals(addOrUpd)){
            if (CommonUtils.checkNull(authorId)){
                throw new ServiceException("非法请求，不能获取权限");
            }
        }

        modelMap.put("addOrUpd", addOrUpd);
        modelMap.put("choiceView", "authorAddUpd");
        if (!CommonUtils.checkNull(authorId)){
            Authority authority = authorityService.getAuthorityById(authorId);
            modelMap.put("authority", authority);
        }

        return "/common/trunk";
    }

    /**
     * 新增权限
     * @param authority
     * @return
     */
    @PostMapping("/addOrUpdAuthority.php")
    @ResponseBody
    @RequiresPermissions(value = {"admin:sys.author:add", "admin:sys.author:upd"}, logical = Logical.OR)
    @RequiresRoles("admin")
    public ResultJson addOrUpdAuthority(Authority authority){
        try {

            String id = authority.getId();
            authorityService.addOrUpdAuthority(authority);
            if (CommonUtils.checkNull(id)){
                return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "新增权限成功", null);
            } else {
                return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "更新权限成功", null);
            }


        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            if (CommonUtils.checkNull(authority.getId())){
                return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "新增权限失败", null);
            } else {
                return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "更新权限失败", null);
            }
        }
    }

    /**
     * 删除权限
     * @param authorId 要删除的权限ID
     * @return
     */
    @PostMapping("/delAuthor.php")
    @ResponseBody
    @RequiresRoles("admin")
    @RequiresPermissions("admin:sys.author:del")
    public ResultJson delAuthor(String authorId){
        try {

            authorityService.delAuthorLogic(authorId);
            return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "删除权限成功", null);


        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "删除权限失败", null);
        }
    }

}
